package com.sharedmobility.servlet;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sharedmobility.dao.UserDAO;
import com.sharedmobility.model.User;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.lang.reflect.Type;
import javax.servlet.annotation.WebServlet;

@WebServlet("/api/login")
public class LoginServlet extends HttpServlet {
    private UserDAO userDAO;
    private Gson gson;
    private static final Type MAP_TYPE = new TypeToken<Map<String, Object>>(){}.getType();

    @Override
    public void init() throws ServletException {
        userDAO = new UserDAO();
        gson = new Gson();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");

        try {
            // 获取请求参数
            Map<String, Object> requestData = gson.fromJson(request.getReader(), MAP_TYPE);
            String username = (String) requestData.get("username");
            String password = (String) requestData.get("password");

            // 验证参数
            if (username == null || username.trim().isEmpty()) {
                throw new Exception("用户名不能为空");
            }
            if (password == null || password.trim().isEmpty()) {
                throw new Exception("密码不能为空");
            }

            // 验证用户
            User user = userDAO.findByUsername(username);
            if (user == null) {
                throw new Exception("用户名或密码错误");
            }
            if (!user.getPassword().equals(password)) {
                throw new Exception("用户名或密码错误");
            }

            // 检查用户状态
            if (user.getStatus() != 1) {
                throw new Exception("账号已被禁用");
            }

            // 创建会话
            HttpSession session = request.getSession();
            session.setAttribute("userId", user.getId());
            session.setAttribute("username", user.getUsername());
            session.setAttribute("role", user.getRole());

            // 打印 Session 信息
            System.out.println("Session ID: " + session.getId());
            java.util.Enumeration<String> attrs = session.getAttributeNames();
            while (attrs.hasMoreElements()) {
                String attr = attrs.nextElement();
                System.out.println("Session Attribute: " + attr + " = " + session.getAttribute(attr));
            }

            // 返回成功响应，并重定向到车辆列表页面
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "登录成功");
            result.put("redirectUrl", "vehicle-list.html");
            
            response.getWriter().write(gson.toJson(result));

        } catch (Exception e) {
            // 返回错误响应
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", e.getMessage());
            
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write(gson.toJson(result));
        }
    }
} 